using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web;
using System.Web.UI.WebControls;

namespace DNJ.Ext
{
    public static class PageHelper
    {
        private const string JQSCRIPT_ID = "__jqScriptBlock__";
        private static string JQSCRIPT_INIT = "<!--" + Environment.NewLine + "/*[DNJ]*/$(function() {});/*[/DNJ]*/" + Environment.NewLine + "//-->";

        public static void AppendJQueryScript(string script, HtmlHead htmlHeader)
        {
            string BASE_URL = HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
            HtmlGenericControl jqScriptBlock = (htmlHeader.FindControl(JQSCRIPT_ID) as HtmlGenericControl);
            if (jqScriptBlock == null)
            {
                jqScriptBlock = new HtmlGenericControl("script");
                jqScriptBlock.ID = JQSCRIPT_ID;
                jqScriptBlock.Attributes.Add("type", "text/javascript");

                Literal scriptText = new Literal();
                scriptText.Text = JQSCRIPT_INIT;

                jqScriptBlock.Controls.Add(scriptText);
            }
            (jqScriptBlock.Controls[0] as Literal).Text = (jqScriptBlock.Controls[0] as Literal).Text.Replace("});/*[/DNJ]*/", Environment.NewLine + script + Environment.NewLine + "});/*[/DNJ]*/");

            
            htmlHeader.Controls.Add(jqScriptBlock);
        }
        public static void AppendJQueryPlugin(string selector, string pluginName, string settings, HtmlHead htmlHeader)
        {
            AppendJQueryScript("$('" + selector + "')." + pluginName + "(" + settings + ");", htmlHeader);
        }
        public static void RegisterHeaderScript(string scriptUrl, HtmlHead htmlHeader)
        {
            string BASE_URL = HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
            HtmlGenericControl Include = new HtmlGenericControl("script");
            Include.Attributes.Add("type", "text/javascript");
            Include.Attributes.Add("src", BASE_URL + scriptUrl);
            htmlHeader.Controls.Add(Include);
        }
        public static void RegisterHeaderCSS(string cssUrl, HtmlHead htmlHeader)
        {
            string BASE_URL = HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
            HtmlGenericControl Include = new HtmlGenericControl("link");
            Include.Attributes.Add("type", "text/css");
            Include.Attributes.Add("rel", "stylesheet");
            Include.Attributes.Add("href", BASE_URL + cssUrl);
            htmlHeader.Controls.Add(Include);
        }
    }
}
